package yazan.com.pdacollector_android.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yazan.com.pdacollector_android.R;
import yazan.com.pdacollector_android.adapter.OrderValidationAdapter;
import yazan.com.pdacollector_android.model.Goods;
import yazan.com.pdacollector_android.utils.PDAGlobal;
import yazan.com.pdacollector_android.utils.ScanDeviceHelper;

public class OrderValidationActivity extends AppCompatActivity {

    //<editor-fold desc=”成员变量”>


    @BindView(R.id.tvIndex)
    TextView tvIndex;
    @BindView(R.id.tvGoodName)
    TextView tvGoodName;
    @BindView(R.id.tvBarcode)
    TextView tvBarcode;
    @BindView(R.id.tvSpecification)
    TextView tvSpecification;
    @BindView(R.id.tvCount)
    TextView tvCount;
    @BindView(R.id.tvValidationCount)
    TextView tvValidationCount;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.header)
    View headerView;
    @BindView(R.id.etCount)
    EditText etCount;
    @BindView(R.id.operaction_bar)
    ConstraintLayout operactionBar;


    private OrderValidationAdapter orderValidationAdapter;


    private List<Goods> goodsList;
    private Goods headerItemData;


    private ScanDeviceHelper scanDeviceHelper;

    //</editor-fold>


    //<editor-fold desc=”生命周期”>


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_validation);
        ButterKnife.bind(this);
        scanDeviceHelper = new ScanDeviceHelper(this, new ScanValidationListener(this));
        configUI();
    }

    @Override
    protected void onStart() {
        super.onStart();
        scanDeviceHelper.registerReceiver();
    }

    @Override
    protected void onStop() {
        super.onStop();
        scanDeviceHelper.unRegisterReceiver();
    }

    //</editor-fold>

    //<editor-fold desc=”私有方法”>

    @SuppressLint("SetTextI18n")
    private void configUI() {

        Intent intent = getIntent();
        goodsList = intent.getParcelableArrayListExtra("goods");
        if (PDAGlobal.selectPosition != -1) {
            headerItemData = goodsList.get(PDAGlobal.selectPosition);
        }
        settingHeader(headerItemData);


        headerView.setBackgroundColor(getResources().getColor(R.color.skyblue));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        ArrayList<Goods> goodsArrayList = null;
        if (headerItemData != null) {
            goodsArrayList = new ArrayList<>();
            for (int i = 0; i < headerItemData.getValidation_count(); i++) {
                goodsArrayList.add(headerItemData);
            }
        }
        orderValidationAdapter = new OrderValidationAdapter(R.layout.item_order_validation, goodsArrayList);
        orderValidationAdapter.bindToRecyclerView(recyclerView);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));


        ItemDragAndSwipeCallback itemDragAndSwipeCallback = new ItemDragAndSwipeCallback(orderValidationAdapter);
        itemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragAndSwipeCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);

        orderValidationAdapter.enableSwipeItem();
        orderValidationAdapter.setOnItemSwipeListener(new OnItemSwipeListener() {
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
                //实际的pos是  length - 1 - pos
                if (!StringUtils.isTrimEmpty(headerItemData.getFgoods_codes())) {

                    String goodsCodes = headerItemData.getFgoods_codes();
                    String[] split = goodsCodes.split("_");
                    List<String> traces = new ArrayList<>();
                    for (int i = 0; i < split.length; i++) {
                        if (StringUtils.isTrimEmpty(split[i])) {
                            continue;
                        }
                        traces.add(split[i]);
                    }

                    String remove = traces.remove(traces.size() - 1 - pos);
                    Log.d("aaaaaaaa", "onItemSwiped()" + remove);


                    StringBuilder result = new StringBuilder();
                    for (int i = 0; i < traces.size(); i++) {
                        result.append(traces.get(i)).append("_");
                    }

                    Log.d("aaaaaaaaa", "onItemSwiped()" + result.toString());
                    headerItemData.setFgoods_codes(result.toString());
                }
                headerItemData.setValidation_count(Math.max(headerItemData.getValidation_count() - 1, 0));
                headerItemData.setValidation_type(0);
                settingHeader(headerItemData);
            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {

            }
        });
    }


    private void settingHeader(Goods good) {
        if (good == null) {
            tvIndex.setText("");
            tvGoodName.setText("");
            tvBarcode.setText("");
            tvSpecification.setText("");
            tvCount.setText("");
            tvValidationCount.setText("");
            etCount.setText("");
            return;
        }

        if (operactionBar.getVisibility() == View.GONE && good.getFiscode() == 0) {
            operactionBar.setVisibility(View.VISIBLE);
        }

        headerItemData = good;
        tvIndex.setText(good.getFIndex() + "");
        tvGoodName.setText(good.getFgoods_name());
        tvBarcode.setText(good.getFgoods_sn());
        tvSpecification.setText(good.getFgoods_spec());
        tvCount.setText(good.getFgoods_qty() + "");
        tvValidationCount.setText(good.getFgoods_qty() + "/" + good.getValidation_count());
        etCount.setText(good.getValidation_count() + "");
        etCount.setSelection(etCount.getText().length());
    }


    @OnClick({R.id.btQR, R.id.btSubmit, R.id.btIncrease, R.id.btDecrease, R.id.btSave})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btQR: {
                scanDeviceHelper.startScan();
//                ScanValidationListener listener = new ScanValidationListener(this);
//                listener.onSuccess("6970461284537");
            }
            break;
            case R.id.btSubmit: {
                jumpToPreviousPage();
            }
            break;
            case R.id.btIncrease: {
                int currentCount = headerItemData.getValidation_count();
                int targetCount = currentCount + 1;
                if (targetCount > headerItemData.getFgoods_qty() || targetCount < 0) {
                    return;
                }
                headerItemData.setValidation_count(targetCount);
                if (headerItemData.getValidation_count() == headerItemData.getFgoods_qty()) {
                    headerItemData.setValidation_type(1);
                }
                settingHeader(headerItemData);
            }
            break;
            case R.id.btDecrease: {
                int currentCount = headerItemData.getValidation_count();
                int targetCount = currentCount - 1;
                if (targetCount > headerItemData.getFgoods_qty() || targetCount < 0) {
                    return;
                }
                headerItemData.setValidation_count(targetCount);
                if (headerItemData.getValidation_count() == headerItemData.getFgoods_qty()) {
                    headerItemData.setValidation_type(1);
                }
                settingHeader(headerItemData);
            }
            break;
            case R.id.btSave: {
                String countStr = etCount.getText().toString();
                if (!RegexUtils.isMatch("^[\\d]*$", countStr)) {
                    ToastUtils.showShort("待扫数必须是整数");
                    return;
                }

                int currentCount = Integer.parseInt(etCount.getText().toString());
                if (currentCount > headerItemData.getFgoods_qty() || currentCount < 0) {
                    ToastUtils.showShort("待扫数取值范围错误！");
                    return;
                }

                headerItemData.setValidation_count(currentCount);
                if (headerItemData.getValidation_count() == headerItemData.getFgoods_qty()) {
                    headerItemData.setValidation_type(1);
                }
                settingHeader(headerItemData);
                jumpToPreviousPage();
            }
            break;
        }
    }

    private void jumpToPreviousPage() {
        Intent intent = new Intent();
        intent.putExtra("good", headerItemData);
        setResult(1, intent);
        finish();
    }


    //</editor-fold>

    //<editor-fold desc=”内部类”>

    private static class ScanValidationListener implements ScanDeviceHelper.ScanDeviceHelperListener {

        private WeakReference<OrderValidationActivity> weakReference;
        ///万能码是为了应对 ,没有码的商品也要验证的情况.
        private final String universalCode = "000000";
        private final String universalTrackCode = "0";

        public ScanValidationListener(OrderValidationActivity context) {
            this.weakReference = new WeakReference<>(context);
        }


        @Override
        public void onSuccess(String content) {
            if (weakReference.get() == null) {
                return;
            }

            String traceCode = "";
            String snCode = content;
            if (content.contains("_")) {
                //追溯
                String[] split = content.split("_");
                if (split.length == 2) {
                    snCode = split[0];
                    traceCode = split[1];
                } else {
                    ToastUtils.showShort("追溯码残缺");
                    return;
                }
            }

            boolean hasTraceCode = !StringUtils.isTrimEmpty(traceCode);

            synchronized (weakReference.get()) {
                OrderValidationActivity orderValidationActivity = weakReference.get();

                if (orderValidationActivity.headerItemData != null) {
                    //有头部数据的时候
                    Goods headerItemData = orderValidationActivity.headerItemData;

                    if (headerItemData.getFiscode() != 1 && hasTraceCode) {
                        ToastUtils.showShort("当前商品非追溯商品");
                        return;
                    }

                    if (headerItemData.getValidation_count() == headerItemData.getFgoods_qty()) {
                        orderValidationActivity.scanDeviceHelper.speak(3);
                        ToastUtils.showShort("不能超过最大数");
                        return;
                    }


                    if (snCode.equals(universalCode) || (headerItemData.getFgoods_sn() != null && headerItemData.getFgoods_sn().equals(snCode))) {

                        if (snCode.equals(universalCode) && headerItemData.getFiscode() == 1) {
                            if (StringUtils.isTrimEmpty(headerItemData.getFgoods_codes())) {
                                headerItemData.setFgoods_codes(universalTrackCode + "_");
                            } else {
                                headerItemData.setFgoods_codes(headerItemData.getFgoods_codes() + universalTrackCode + "_");
                            }
                        } else {
                            if (hasTraceCode) {
                                if (StringUtils.isTrimEmpty(headerItemData.getFgoods_codes())) {
                                    headerItemData.setFgoods_codes(traceCode + "_");
                                } else if (!headerItemData.getFgoods_codes().contains(traceCode)) {
                                    headerItemData.setFgoods_codes(headerItemData.getFgoods_codes() + traceCode + "_");
                                } else {
                                    //如果已经包含了这个追溯码了,就不处理了，跳出逻辑。
                                    ToastUtils.showShort("此追溯码已经扫过了");
                                    return;
                                }
                            }
                        }

                        headerItemData.setValidation_count(headerItemData.getValidation_count() + 1);
                        if (headerItemData.getValidation_count() == headerItemData.getFgoods_qty()) {
                            headerItemData.setValidation_type(1);
                        }
                        orderValidationActivity.settingHeader(headerItemData);
                        orderValidationActivity.orderValidationAdapter.addData(0, headerItemData);
                        orderValidationActivity.recyclerView.scrollToPosition(0);
                        orderValidationActivity.scanDeviceHelper.speak(1);
                    } else {
                        orderValidationActivity.scanDeviceHelper.speak(2);
                        ToastUtils.showShort("扫描的数据与当前商品的sn码不符!");
                    }

                } else {
                    Goods headerItemData = null;
                    for (Goods good : orderValidationActivity.goodsList) {
                        if (good.getFgoods_sn() != null && good.getFgoods_sn().equals(snCode)) {
                            if ((good.getFiscode() == 1 && hasTraceCode) || (good.getFiscode() != 1 && !hasTraceCode)) {
                                headerItemData = good;
                                break;
                            }
                        }
                    }

                    if (headerItemData == null) {
                        ToastUtils.showShort("您扫的二维码不是本订单所属的!如商品携带追溯属性，请使用追溯二维码！");
                        orderValidationActivity.scanDeviceHelper.speak(2);
                    } else {
                        if (headerItemData.getValidation_count() == headerItemData.getFgoods_qty()) {
                            orderValidationActivity.scanDeviceHelper.speak(3);
                            ToastUtils.showShort("不能超过最大数");
                            return;
                        }

                        if (hasTraceCode) {
                            if (StringUtils.isTrimEmpty(headerItemData.getFgoods_codes())) {
                                headerItemData.setFgoods_codes(traceCode + "_");
                            } else if (!headerItemData.getFgoods_codes().contains(traceCode)) {
                                headerItemData.setFgoods_codes(headerItemData.getFgoods_codes() + traceCode + "_");
                            } else {
                                //如果已经包含了这个追溯码了,就不处理了，跳出逻辑。
                                ToastUtils.showShort("此追溯码已经扫过了");
                                return;
                            }
                        }
                        headerItemData.setValidation_count(headerItemData.getValidation_count() + 1);
                        if (headerItemData.getValidation_count() == headerItemData.getFgoods_qty()) {
                            headerItemData.setValidation_type(1);
                        }
                        orderValidationActivity.settingHeader(headerItemData);
                        orderValidationActivity.orderValidationAdapter.addData(0, headerItemData);
                        orderValidationActivity.recyclerView.scrollToPosition(0);
                        orderValidationActivity.scanDeviceHelper.speak(1);
                    }
                }
            }
        }
    }

    //</editor-fold>
}
